﻿using System;
using System.Collections.Generic;
using System.Windows.Input;
using BHS.TFSChangsetAnalyser.Model;
using NLog;

namespace BHS.TFSChangsetAnalyser.ViewModel
{
    public class AnalyseCommand : ICommand
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        private readonly IMainWindowViewModel _viewModel;
        private readonly IErrorPresenter _errorPresenter;

        public AnalyseCommand(IMainWindowViewModel viewModel,
                              IErrorPresenter errorPresenter)
        {
            _viewModel = viewModel;
            _errorPresenter = errorPresenter;
        }

        public void Execute(object parameter)
        {
            Logger.Info("Start Execute");

            _viewModel.IsBusy = true;

            _viewModel.AnalysisResults.ClearAnalysisResults();

            IEnumerable<ChangesetInfo> changesets = null;
            try
            {
                changesets = _viewModel.Importer.GetChangesets();

                foreach (ChangesetInfo changesetInfo in changesets)
                {
                    Logger.Info("Retrieved Changeset: {0}", changesetInfo.ChangesetId);
                    _viewModel.AnalysisResults.AddChangesetForAnalysis(changesetInfo);
                }
            }
            catch (Exception e)
            {
                _errorPresenter.Show(e.Message);
            }
            finally
            {
                _viewModel.IsBusy = false;
            }

            Logger.Info("End Execute");
        }

        public bool CanExecute(object parameter)
        {
            return _viewModel.TfsServerConnectionDetails.HasServerNameAndProjectPath &&
                   _viewModel.TfsServerConnectionDetails.HasUserCredentials;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }
}
